package cn.com.headfree.service.controller;

import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.config.DateJsonValueProcessor;
import com.gta.edu.sdk.util.EhCacheUtil;
import com.gta.edu.sdk.util.RedisClusterUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.entity.LogInfo;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * Title: Description: 用户信息访问接口 Copyright: Copyright (c) 2017 Company:
 * www.headfree.com.cn
 * 
 * @author fengya
 * @version 1.0
 * @date 2019年8月8日 上午8:10:34
 */
@RestController
@RequestMapping(value = "/user", produces = "application/json;charset=UTF-8")
public class UserAuthController {
	private static final Logger LOG = Logger.getLogger(UserAuthController.class);

	@Value("${local.ip}")
	private String localIp;
//	private String appId;
//	@Value("${user.redis.time}")
//	private String userRedisTime;
//	@Value("${isc.ip}")
//	private String iscIp;
//	@Value("${isc.sso.iscFrontmvServ}")
//	private String iscFrontmvServ;
//	@Value("${redis.key.user.auth.pre}")
//	private String redisUserAuthPre;
	@Value("${redis.key.user.info.pre}")
	private String redisUserInfoPre;
//	@Autowired
//	private Environment environment;

//	@RequestMapping(value="/getRedis",method=RequestMethod.GET)
//	public void getRedis() {
//		RedisClusterUtil.getInstance().set("name", "yalin");
//		RedisClusterUtil.getInstance().setString("sex", "male");
//		RedisClusterUtil.getInstance().expire("sex", 1800);
//		LOG.info("name=" + RedisClusterUtil.getInstance().get("name"));
//		LOG.info("sex=" + RedisClusterUtil.getInstance().getString("sex"));
//	}

	/**
	 * @description 得到当前登录用户信息
	 * @author 冯亚
	 * @date 2019年8月8日 上午8:12:30
	 * @param token
	 * @return ResultData
	 */
	@RequestMapping(value = "/getLoginUser", method = RequestMethod.GET)
	public ResultData getLoginUser(@RequestParam(required = true) String token, HttpServletRequest request) {
		ResultData data = new ResultData();
		LogInfo logInfo = new LogInfo();
		String logId = UUID.randomUUID().toString();
		logInfo.setId(logId);
		logInfo.setSip(request.getRemoteAddr());
		logInfo.setDip(localIp);
		logInfo.setDip_service("/user-auth-server/user/getLoginUser");
		logInfo.setLogType(LogType.receive.toString());
		logInfo.setTime(new Date());
		JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		try {
			String loginUserJson = null;
			String loginUserKey = redisUserInfoPre + token;
			loginUserJson = EhCacheUtil.getValue(loginUserKey);
			if (!StringUtil.isNullOrEmpty(loginUserJson)) {
				data.setData(loginUserJson);
				return data;
			}
			int count = 1;
			loginUserJson = RedisClusterUtil.getInstance().getString(redisUserInfoPre + token);
			while (StringUtils.isBlank(loginUserJson)) {
				count++;
				Thread.sleep(10000);
				if (count >= 3) {
					break;
				}
				loginUserJson = RedisClusterUtil.getInstance().getString(redisUserInfoPre + token);
			}
			if (StringUtils.isBlank(loginUserJson)) {
				data.setSuccess(false);
				data.setErrorMsg("获取的用户信息为空！");
				logInfo.setLevel(LogLevel.WARN.toString());
				logInfo.setLogMessage("根据传递的参数【" + token + "】获取登录用户信息为空！");
			} else {
				EhCacheUtil.put(loginUserKey, loginUserJson);
				data.setData(loginUserJson);
				logInfo.setLevel(LogLevel.INFO.toString());
				logInfo.setLogMessage(loginUserJson);
			}
			LOG.info(JSONObject.fromObject(logInfo, cfg).toString());
		} catch (Exception e) {
			data.setErrorMsg("获取当前登录用户出现了异常！");
			data.setSuccess(false);
			logInfo.setLevel(LogLevel.ERROR.toString());
			logInfo.setLogMessage(e.getMessage());
			LOG.error(JSONObject.fromObject(logInfo, cfg).toString(), e);
		}
		return data;
	}

//	/**
//	 * @description 根据登录用户ID，获取当前登录用户的菜单权限信息
//	 * @author 冯亚
//	 * @date 2019年8月9日 上午8:35:45
//	 * @param appId
//	 * @param userId
//	 * @param request
//	 * @return ResultData
//	 */
//	@RequestMapping(value = "/getLoginUserAuth", method = RequestMethod.GET)
//	public ResultData getLoginUserAuth(@RequestParam(required = true) String userId,
//			@RequestParam(required = true) String moduleTag, HttpServletRequest request) {
//		ResultData data = new ResultData();
//		String sessionKey = userId + "_" + moduleTag;
//		LogInfo logInfo = new LogInfo();
//		String logId = UUID.randomUUID().toString();
//		logInfo.setId(logId);
//		logInfo.setSip(request.getRemoteAddr());
//		logInfo.setDip(localIp);
//		logInfo.setDip_service("/user-auth-server/user/getLoginUserAuth");
//		logInfo.setLogType(LogType.receive.toString());
//		logInfo.setTime(new Date());
//		JsonConfig cfg = new JsonConfig();
//		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
//		HttpSession session = request.getSession();
//		try {
//			String loginUserAuthJson = null;
//			String loginUserAuthJsonResult = null;
//			if (session.getAttribute(sessionKey) == null) {
//				Object obj = RedisClusterUtil.getInstance().hmgetString(redisUserAuthPre + userId, moduleTag);
//				if (obj == null) {
//					loginUserAuthJsonResult = this.getUserAuthFromISC(userId, moduleTag, request);
//					if (StringUtils.isEmpty(loginUserAuthJsonResult)) {
//						data.setSuccess(false);
//						data.setErrorMsg("获取当前登录用户的权限数据为空，请确认是否已经在统一权限进行了配置！");
//						logInfo.setLevel(LogLevel.WARN.toString());
//						logInfo.setLogMessage("获取当前登录用户【" + userId + "】的权限数据为空，请确认是否已经在统一权限进行了配置！");
//					} else {
//						org.json.JSONObject loginUserAuthJsonObj = new org.json.JSONObject(loginUserAuthJsonResult);
//						if (loginUserAuthJsonObj.getInt("resultCode") == 200) {
//							org.json.JSONArray loginUserAuthJsonArr = loginUserAuthJsonObj.getJSONArray("data");
//							RedisClusterUtil.getInstance().hmsetString(redisUserAuthPre + userId, moduleTag,
//									loginUserAuthJsonArr.toString());
//							RedisClusterUtil.getInstance().expire(redisUserAuthPre + userId,
//									this.userRedisTime == null ? 1980 : Integer.parseInt(this.userRedisTime));
//							session.setAttribute(sessionKey, loginUserAuthJsonArr.toString());
//							data.setData(loginUserAuthJsonArr.toString());
//						} else {
//							data.setSuccess(false);
//							data.setErrorMsg(
//									"获取当前登录用户的权限数据，在统一权限处返回错误信息：" + loginUserAuthJsonObj.getString("resultInfo"));
//						}
//						logInfo.setLevel(LogLevel.INFO.toString());
//						logInfo.setLogMessage("从统一权限平台获取数据:" + loginUserAuthJson);
//					}
//				} else {
//					loginUserAuthJson = obj.toString();
//					session.setAttribute(sessionKey, loginUserAuthJson);
//					data.setData(loginUserAuthJson);
//					logInfo.setLevel(LogLevel.INFO.toString());
//					logInfo.setLogMessage("从redis上获取的数据" + loginUserAuthJson);
//				}
//			} else {
//				loginUserAuthJsonResult = session.getAttribute(sessionKey).toString();
//				RedisClusterUtil.getInstance().expire(redisUserAuthPre + userId,
//						this.userRedisTime == null ? 1980 : Integer.parseInt(this.userRedisTime));
//				data.setData(loginUserAuthJsonResult);
//				logInfo.setLevel(LogLevel.INFO.toString());
//				logInfo.setLogMessage("从session容器中获取的数据：" + loginUserAuthJson);
//			}
//			LOG.info(JSONObject.fromObject(logInfo, cfg).toString());
//		} catch (Exception e) {
//			logInfo.setLevel(LogLevel.ERROR.toString());
//			logInfo.setLogMessage(e.getMessage());
//			LOG.error(JSONObject.fromObject(logInfo, cfg).toString(), e);
//		}
//		return data;
//	}
//
//	/**
//	 * @description 从统一权限平台获取用户权限数据
//	 * @author 冯亚
//	 * @date 2019年8月9日 上午9:47:02
//	 * @param userId
//	 * @param request
//	 * @return String
//	 */
//	private String getUserAuthFromISC(String userId, String moduleTag, HttpServletRequest request) {
//		LogInfo logInfo = new LogInfo();
//		String logId = UUID.randomUUID().toString();
//		logInfo.setId(logId);
//		logInfo.setDip(iscIp);
//		logInfo.setDip_service("/user_access_auth/getUserResource");
//		logInfo.setLogType(LogType.send.toString());
//		logInfo.setTime(new Date());
//		JsonConfig cfg = new JsonConfig();
//		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
//		appId = environment.getProperty("isc.sso." + moduleTag + ".appId");
//		String url = "userResource/all/" + userId + "/" + appId;
//		String result = null;
//		try {
//			result = IscSsoCall.call(url, moduleTag);
//			logInfo.setLevel(LogLevel.INFO.toString());
//			logInfo.setLogMessage(result);
//			LOG.info(JSONObject.fromObject(logInfo, cfg).toString());
//		} catch (Exception e) {
//			logInfo.setLevel(LogLevel.ERROR.toString());
//			logInfo.setLogMessage(e.getMessage());
//			LOG.error(JSONObject.fromObject(logInfo, cfg).toString(), e);
//		}
//		return result;
//	}

	enum LogType {
		send, receive
	}

	enum LogLevel {
		FATAL, ERROR, WARN, INFO, DEBUG
	}
}
